//
//  FormViewConEx.swift
//  Extend
//
//  Created by shufang zou on 2017/8/7.
//  Copyright © 2017年 敬信. All rights reserved.
//

import UIKit

public typealias NewFormItem = () -> (FormEx);

open class FormViewConEx: TableViewConEx<Any, IBCellHolder> {
    
     var relateMap: Dictionary<String, FormEx> = Dictionary();
    
    var cells = [NewFormItem]();
    
    override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cells.count;
    }
    
    override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let item = self .getItem(indexPath);
        let tableId = item?.getTableId();
        
        var reusableCell = tableView.dequeueReusableCell(withIdentifier: tableId!);
    
        // 判断是否需要初始化
        if reusableCell == nil {
            
            reusableCell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier:tableId!);
            
            item?.initItem(reusableCell as! FormCellEx);
            
        }
        item?.refreshItem(reusableCell as! FormCellEx);
        return reusableCell!;
    }
    
    override public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let tabcell = self.tableView(tableView, cellForRowAt: indexPath);
        return tabcell.frame.size.height;
        
        let item = self.getItem(indexPath);
        let cellHeight = Int((item?.height)!);
        return CGFloat(cellHeight);
    }
    
    override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = self.getItem(indexPath);
        if ((item?.onClick) != nil) {
            item?.onClick!();
        }
    }
    
    open func addItem(_ item: @escaping NewFormItem) {
        if (item().related != nil) {
           relateMap.updateValue(item(), forKey: item().related as! String);
        }
        cells.append(item);
    }
    
    open func newBuilder() -> ListConfigureBuilder? {
        return nil;
    }
  
    open func initItems() {
        
    }

//    open func refreshItem(_ item : FormEx) {
//        let index = self.cells.index(of: item);
////        let indexPath = [NSIndexPath ]
//		
//    }
    
    
    open func getItem(_ indexPath: IndexPath) -> FormEx? {
        return self.cells[indexPath.row]();
    }
    
//
//    open func getRelatedItem(_ related :NSString) -> FormEx? {
//        
//    }

}
